package com.safx.entity.tags;

import java.lang.reflect.InvocationTargetException;

import org.apache.log4j.Logger;

import com.safx.entity.enums.ResultEnum;
import com.safx.utility.DataProviderTool;
import com.thoughtworks.selenium.SeleniumException;

public class Html extends ABaseTag {

	Logger logger = Logger.getLogger(Html.class);
	//command标签的值
	private String command;
	//target标签的值
	private String target;
	//value标签的值
	private String value;

	public String getTag() {
		return "Html";
	}

	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	/**
	 * 执行该对象前，把临时变量替换掉
	 * 
	 * <b></b><br/>
	 * 
	 * @Author chenyue ( yue.chen2@hisoft.com ) Create on 2011-8-30
	 */
	private void replaceProperty() {// 执行该对象前，把临时变量替换掉
		this.target = DataProviderTool.getProperty(target);
		this.value = DataProviderTool.getProperty(value);
	}

	@Override
	public String excute() {// 对象的执行方法
		beforeExcute();// 把对象状态从NOTRUN改成FAIL。
		replaceProperty();// 导入临时变量
		String returnStr = "" + ResultEnum.FAIL;
		logger.info(toString());
		try {
			returnStr = reflectMethod(command, target, value,"Html");// 通过反射条用对应的方法
			this.setResult(ResultEnum.PASS);
			append(returnStr);
		} catch (SecurityException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			logger.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			logger.error(e.getMessage(), e);
		} catch (InvocationTargetException e) {
			// 抓到这个异常，说明程序执行时，发生了异常需要处理
			Throwable target = e.getTargetException();
			if (target instanceof SeleniumException) {
				// 处理selenium异常。
				returnStr = ((SeleniumException) target).getMessage();
				logger.error(returnStr, (SeleniumException) target);
				append(returnStr);
				this.setResult(ResultEnum.FAIL);// 把状态置为fail，顺便截图，记录截图的编号。
				// throw (SeleniumException) target;
			} else {
				logger.error(e.getMessage(), e);// 记录未处理异常
			}
		} catch (NoSuchMethodException e) {
			logger.error(e.getMessage(), e);
		}
		return returnStr;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return command + " | " + target + " | " + value;
	}

	public Html clone() {
		Html h = new Html();
		h.setCommand(this.command);
		h.setLineNumb(this.getLineNumb());
		h.setTarget(this.target);
		h.setValue(this.value);
		h.setInfo(this.getInfo());
		return h;
	}
}
